<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Config;
use app\admin\model\Order;
use app\admin\model\MessageApi;

class OrderStock extends Command
{
    public $client;

    protected function configure()
    {
        $this->setName('OrderStock')->setDescription('订单任务');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->_log('<meta charset="UTF-8">');
        $this->_log('启动进程');
        set_time_limit(0);
        error_reporting(E_ALL);

        $redis = new \redis();
        $redis->connect('127.0.0.1', '6379');

        $uniacids = Db::name('config')->group('uniacid')->column('uniacid');
        while (true) {
            foreach ($uniacids as $uniacid) {
                $uniacid_config = Db::name('config')->where('uniacid', $uniacid)->column('value', 'name');
                $service_port = $uniacid_config['tcp_port'];
                $address = $uniacid_config['tcp_ip'];

                // 待消费
                $list = Db::name('order')
                    ->alias('a')
                    ->field("a.id,b.closing_command,a.x_status,a.command_closing_num,b.dian_id,b.category_id")
                    ->join('fangjian b ', 'b.id= a.fangjian_id')
                    ->where("a.status = '1'  and UNIX_TIMESTAMP(a.fuwu) < UNIX_TIMESTAMP(NOW())")
                    ->where('a.uniacid', $uniacid)
                    ->order("a.fuwu asc")
                    ->select();

                if ($list) {
                    foreach ($list as $item) {
                        $this->_log('--------');
                        $this->_log("订单ID:" . $item['id'] . ",订单状态：待消费");
                        $port = Db::name('category')->where('uniacid', $uniacid)->where("id = {$item['category_id']}")->value('port');
                        if ($port && $item['dian_id'] && 1 != $item["x_status"] && $item['command_closing_num'] < 3) {
                            $res = $this->send($this->closing_command($item['dian_id']), $port);
                        } else {
                            $this->_log("TCP无需发送");
                            $res = true;
                        }
                        if ($res === true) {
                            $rs = Order::where('id', $item['id'])->where('uniacid', $uniacid)->update([
                                'is_write_off' => 1,
                                'status' => 2
                            ]);
                            if ($rs) {
                                $this->_log("订单状态：消费中");
                            } else {
                                $this->_log("订单状态：修改失败");
                            }
                        } else {
                            Order::where('id', $item['id'])->where('uniacid', $uniacid)->update([
                                'command_closing_num' => $item['command_closing_num'] + 1
                            ]);
                        }
                    }
                    $this->_log("待消费订单转消费中-完成");
                }

                unset($list);
                $list = Db::name('order')
                    ->alias('a')
                    ->field("a.id,b.dian_id,b.opening_command,a.fuwu,a.fuwu_sc,
                a.x_status,a.is_message,b.message_devid,a.command_opening_num,a.fangjian_id,b.category_id,b.clean_time")
                    ->join('fangjian b ', 'b.id= a.fangjian_id', "left")
                    ->where(['a.status' => '2'])
                    ->where('a.uniacid', $uniacid)
                    ->select();
                $end_time_min = Db::name("config")->where('uniacid', $uniacid)->where("name", "end_time_min")->value("value");
                $end_time_content = Db::name("config")->where('uniacid', $uniacid)->where("name", "end_time_content")->value("value");


                $oMessageApi = new MessageApi();

                if ($list) {
                    foreach ($list as $item) {

                        $item['fuwu'] = strtotime($item['fuwu']);
                        $jtime = $item['fuwu'] + $item['fuwu_sc'] * 60 * 60;
                        $message_time = $jtime - intval($end_time_min) * 60;

                        if ($message_time < time() && $item['is_message'] == 0) {
                            if (1 != $item['x_status'] && $item['message_devid']) {
                                $this->_log("订单ID:" . $item['id'] . ",发送提示" . date("Y-m-d H:i:s", $message_time) . ",内容：" . $end_time_content);
                                $oMessageApi->send($item['message_devid'], $end_time_content);
                            }
                            $rs = Order::where('id', $item['id'])->where('uniacid', $uniacid)->update(['is_message' => 1]);
                        }

                        if (time() > $jtime) {
                            $this->_log('--------');
                            $this->_log("订单ID:" . $item['id'] . ",订单状态：消费中");
                            $port = Db::name('category')->where('uniacid', $uniacid)->where("id = {$item['category_id']}")->value('port');
                            if ($port && $item['dian_id'] && 1 != $item['x_status'] && $item['command_opening_num'] < 3) {
                                $res = $this->send($this->opening_command($item['dian_id']), $port);
                            } else {
                                $this->_log("TCP无需发送");
                                $res = true;
                            }
                            if ($res === true) {
                                $rs = Order::where('id', $item['id'])->where('uniacid', $uniacid)->update(['status' => 3]);
                                if ($rs) {
                                    $this->_log("订单状态：完成");
                                } else {
                                    $this->_log("订单状态：修改失败");
                                }

                                // 打扫时间
                                if (1 != $item['x_status']) {
                                    Db::name('fangjian')->where('id', $item['fangjian_id'])->update([
                                        'is_dasao' => 1
                                    ]);
//                                        $san_time = floatval($item['clean_time']);
//                                        if ($san_time > 0) {
//                                            $isScan = $this->checkTime($item['fangjian_id'], $jtime, $san_time);
//                                            if ($isScan) {
//                                                Db::name('look_time')->insert([
//                                                    "fangjian_id" => $item['fangjian_id'],
//                                                    "start_time" => date('Y/m/d H:i:s', $jtime),
//                                                    "end_time" => $san_time,
//                                                    "remark" => '打扫',
//                                                    "uniacid" => $uniacid,
//                                                ]);
//                                                $this->_log("打扫Time：{$san_time}min");
//                                            }
//                                        }
                                    // 通知打扫人员
                                    $staff_list = Db::name('staff')->where('uniacid', $uniacid)->where('category_id', $item['category_id'])->where('state', 1)->select();
                                    if ($staff_list) {
                                        // 发送通知接口
                                        foreach ($staff_list as $staff) {
                                            $mobile = $staff['username'];
                                            (new \app\admin\model\VmsClientApi())->send($mobile);
                                            $this->_log("电话通知：：{$mobile}");
                                        }
                                    }
                                }
                            } else {
                                Order::where('id', $item['id'])->where('uniacid', $uniacid)->update([
                                    'command_opening_num' => $item['command_opening_num'] + 1
                                ]);
                            }
                        }
                    }
                }


                $ims_ymq_changdi_diancommand = Db::name('diancommand')
                    ->alias('a')
                    ->field("a.id,a.status,b.closing_command,b.opening_command,a.send_num,b.dian_id,b.category_id")
                    ->join('fangjian b ', 'b.id= a.fangjian_id', "left")
                    ->where(['a.is_status' => 0])
                    ->where('a.uniacid', $uniacid)
                    ->select();
                if ($ims_ymq_changdi_diancommand) {
                    foreach ($ims_ymq_changdi_diancommand as $item) {
                        $this->_log('--------');
                        // $this->_log("手动发送ID:" . $item['id']);
                        $res = false;
                        $port = Db::name('category')->where('uniacid', $uniacid)->where('id', $item['category_id'])->value('port');
                        if ($port && $item['dian_id'] && 1 == $item["status"] && $item['send_num'] < 3) {
                            $res = $this->send($this->closing_command($item['dian_id']), $port);
                        }
                        if ($port && $item['dian_id'] && 2 == $item['status'] && $item['send_num'] < 3) {
                            $res = $this->send($this->opening_command($item['dian_id']), $port);
                        }
                        if ($res === true) {
                            $rs = Db::name('diancommand')->where('uniacid', $uniacid)->where('id', $item['id'])->update(['is_status' => 1, "send_time" => time()]);
                            if ($rs) {
                                $this->_log("状态：完成");
                            } else {
                                $this->_log("状态：失败");
                            }
                        } else {
                            $is_status = 0;
                            if ($item['send_num'] > 3) {
                                $is_status = 2;
                            }
                            Db::name('diancommand')->where('uniacid', $uniacid)->where('id', $item['id'])->update([
                                'send_num' => $item['send_num'] + 1,
                                'is_status' => $is_status
                            ]);
                        }
                    }
                }

                sleep(1);
            }


        }
    }

    public function closing_command($dian_id)
    {
        $dian_id = str_pad($dian_id, 4, "0", STR_PAD_LEFT);
        $data5 = $this->calCheckSum($dian_id . '0500');
        $command = "7E {$dian_id} 05 00 {$data5} 0D ";
        $this->_log("指令：$command");
        return $command;
    }

    public function opening_command($dian_id)
    {
        $dian_id = str_pad($dian_id, 4, "0", STR_PAD_LEFT);
        $data5 = $this->calCheckSum($dian_id . '0501');
        $command = "7E {$dian_id} 05 01 {$data5} 0D";
        $this->_log("指令：$command");
        return $command;
    }

    public function checkTime($fangjian_id, $k_time, $fuwu_sc = 0)
    {
        $order = Db::name('order')->field('id,fuwu,fuwu_sc')->where([
            'fangjian_id' => $fangjian_id,
            'status' => ['in', ['1', '2', '5']]
        ])->where("UNIX_TIMESTAMP(fuwu) > " . time())->select();

        $astart = $k_time;//第1个开始
        $aend = $k_time + $fuwu_sc * 60 * 60;//第1个结束
        $aend = $aend - 1;
        $res = true;
        foreach ($order as &$v) {
            $q_time = strtotime($v['fuwu']);
            $f_time = $q_time + $v['fuwu_sc'] * 60;
            $bstart = $q_time;//第2个开始
            $bend = $f_time;//第2个结束
            $isIntersection = false;
            if ($bstart - $astart > 0) {
                if ($bstart - $aend <= 0) {
                    $isIntersection = true;
                }
            } else {
                if ($bend - $astart > 0) {
                    $isIntersection = true;
                }
            }
            if ($isIntersection == true) {
                $res = false;
            }
        }
        return $res;
    }


    public function send($command, $tcp_port)
    {
        try {
            $service_port = $tcp_port; //这里是端口号
            $address = Config::get('site.tcp_ip');//这里输入服务器端IP地址
            $this->_log("地址：{$address}");
            $this->_log("端口：{$service_port}");
            $client = stream_socket_client("tcp://{$address}:{$service_port}", $errno, $errmsg, 1);
            fwrite($client, str_replace(' ', '', $command) . "\n");
            $recv = fread($client, 8192);
            if ($recv) {
                $this->_log("TCP返回:" . $recv);
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            var_dump($exception->getMessage());
            return false;
        }
    }

    //获取校验码
    public function calCheckSum($hex_string)
    {
        $cs = 0;
        $str_len = strlen($hex_string);
        for ($i = 0; $i < $str_len; $i += 2) {
            $cs += hexdec(substr($hex_string, $i, 2));
        }
        $n = (hexdec(bin2hex(pack('C', $cs))));
        $check_sub_in_pkg = substr($n, strlen($n) - 2, 2);
        return str_pad($check_sub_in_pkg, 2, "0", STR_PAD_LEFT);
    }


    public function _log($txt)
    {
        $log_path = ROOT_PATH . "public/stock . html";
        $text = date('Y-m-d H:i:s') . "：" . $txt;
        echo $text . PHP_EOL;
        file_put_contents($log_path, $text . " < br>", FILE_APPEND);
    }

}
